<template>
  <div class="requestAdd">
    <!-- 筛选按钮 -->
    <!-- <div class="search-button"></div> -->
    <el-collapse v-model="activeNames">
      <el-collapse-item name="1" class="transform-down">
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">申请信息</span>
        </template>
        <div class="request-info">
          <el-form
            :model="dtlForm"
            ref="dtlFormRef"
            :rules="queryRules"
            label-width="100px"
            v-enterToNext
          >
            <el-row>
              <el-col :span="6">
                <el-form-item label="退库编号：" label-width="110px">
                  <el-input
                    :disabled="true"
                    v-model="dtlForm.stockReturnCode"
                    placeholder=""
                    clearable
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="入库批次：" label-width="120px">
                  <el-input
                    :disabled="true"
                    v-model="dtlForm.batchCode"
                    placeholder=""
                    clearable
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="入库人：" label-width="110px">
                  <el-input
                    :disabled="true"
                    v-model="dtlForm.applicantName"
                    placeholder=""
                    clearable
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="入库部门：" label-width="110px">
                  <el-input
                    :disabled="true"
                    v-model="dtlForm.deptName"
                    placeholder=""
                    clearable
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="入库日期："
                  prop="applicantDate"
                  label-width="110px"
                >
                  <el-date-picker
                    v-model="dtlForm.applicantDate"
                    format="YYYY/MM/DD HH:mm:ss"
                    class="search-input"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    type="datetime"
                    placeholder="请选择"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="本次退库数量：" label-width="120px">
                  <el-input
                    :disabled="true"
                    v-model="dtlForm.inQty"
                    placeholder=""
                    clearable
                    class="search-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="仓库："
                  prop="warehouseId"
                  label-width="110px"
                >
                  <el-select
                    v-model="dtlForm.warehouseId"
                    placeholder="请选择"
                    clearable
                    class="search-input"
                    @change="handleWarehouseChange"
                  >
                    <el-option
                      v-for="dict in warehouseList"
                      :key="dict.warehouseId"
                      :label="dict.warehouseCode"
                      :value="dict.warehouseId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="dtlForm.importantDevice === 1">
                <el-form-item
                  label="厂家保质期："
                  prop="expireDate"
                  label-width="110px"
                >
                  <el-input
                    clearable
                    v-model="dtlForm.expireDate"
                    class="search-input"
                    maxlength="30"
                    disabled
                    placeholder=""
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6" v-if="dtlForm.importantDevice === 1">
                <el-form-item
                  label="授权有效期："
                  prop="validityPeriod"
                  label-width="110px"
                >
                  <el-input
                    v-model="dtlForm.validityPeriod"
                    placeholder=""
                    disabled
                    clearable
                    class="search-input"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="6" v-if="dtlForm.importantDevice === 1">
                <el-form-item
                  label="主设备序列号："
                  prop="materialNumber"
                  label-width="120px"
                >
                  <el-input
                    v-model="dtlForm.materialNumber"
                    placeholder=""
                    clearable
                    class="search-input"
                    @change="handleMasterChange"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="备注：" label-width="110">
                  <el-input
                    v-model="dtlForm.remarks"
                    placeholder=""
                    style="width: 100%"
                    clearable
                    type="textarea"
                    maxlength="2000"
                    class="search-input"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item
                  label="上传图片："
                  prop="businessLicense"
                  label-width="110"
                >
                  <Upload
                    :fileList="dtlForm.fileList"
                    :isFull="true"
                    :isCanDelete="true"
                    :showButton="true"
                    :limit="1"
                    accept=".jpg,.png"
                    @success="(result) => uploadSuccess(result, 9)"
                    @deleteFile="(result) => uploadRemove(result, 9)"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-collapse-item>
      <el-collapse-item
        name="2"
        style="position: relative"
        class="transform-down"
      >
        <template #title>
          <span class="circle"></span>
          <span class="collapse-title">物料列表</span>
          <div class="nofixed-search-button button-position">
            <el-button
              class="btn submit"
              @click.stop="handleAdd(dtlFormRef, 2)"
              v-if="dtlForm.importantDevice == 1"
              v-loading="loadingCheck"
              ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
              >添加</el-button
            >
            <el-button
              class="btn submit"
              @click.stop="handleAdd(dtlFormRef, 3)"
              v-if="dtlForm.importantDevice != 1"
              v-loading="loadingCheck"
              ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
              >添加</el-button
            >
            <el-button class="btn direction" @click="handleBack"
              ><el-icon class="icon" color="#fff"> <Back /> </el-icon
              >关闭</el-button
            >
          </div>
        </template>
        <div class="contact-info">
          <!-- 表格数据 -->
          <el-table
            :data="dtlForm.dtlList"
            border
            :height="'330px'"
            :header-cell-style="{ 'text-align': 'center' }"
            :header-cell-class-name="cellClass"
            ref="multipleTableRef"
            :row-style="rowClass"
          >
            <el-table-column
              v-if="false"
              type="selection"
              :selectable="checkSelect"
              width="85"
              align="center"
            />
            <el-table-column
              label="操作"
              align="center"
              :show-overflow-tooltip="true"
              width="100px"
            >
              <template #default="{ row, $index }">
                <div class="table-operate" v-if="row.status == 1">
                  <img
                    src="@/assets/icons/images/edit.png"
                    class="table-icon"
                    title="修改"
                    @click="handleEdit(row, $index)"
                  />
                </div>
              </template>
            </el-table-column>
            <!-- 操作模式 -->

            <el-table-column
              v-if="dtlForm.importantDevice == 1"
              label="主设备物资序列号"
              align="center"
              :show-overflow-tooltip="true"
              width="100px"
            >
              <template #default="{ row, $index }">
                <div class="table-operate">
                  <el-button
                    v-if="row.materialNumber"
                    @click="handleQrcode(row, $index)"
                    style="background-color: #b0e0e6"
                    >查看</el-button
                  >
                  <el-button v-else disabled style="background-color: #ccc">
                    查看
                  </el-button>
                </div>
              </template></el-table-column
            >

            <el-table-column
              label="序号"
              type="index"
              :show-overflow-tooltip="true"
              min-width="60"
            />
            <el-table-column
              label="物料编号"
              prop="materialCode"
              :show-overflow-tooltip="true"
              min-width="100"
            >
              <template #default="{ row }">
                <span>{{ row.materialCode ? row.materialCode : "--" }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="物料名称"
              prop="materialName"
              :show-overflow-tooltip="true"
              min-width="160"
            />
            <el-table-column
              label="出厂型号"
              prop="factoryCode"
              :show-overflow-tooltip="true"
              min-width="120"
            />
            <el-table-column
              label="技术参数"
              prop="technologyParameter"
              :show-overflow-tooltip="true"
              min-width="120"
            />
            <el-table-column
              label="单位"
              prop="materialUnitName"
              :show-overflow-tooltip="true"
              min-width="60"
            />

            <el-table-column
              label="采购单价（元）"
              prop="purchasePrice"
              :show-overflow-tooltip="true"
              min-width="120"
            />
            <el-table-column
              label="申请退库数量"
              prop="stockReturnQuantity"
              :show-overflow-tooltip="true"
              min-width="120"
            />
            <el-table-column label="入库数量" prop="inQty" min-width="120">
            </el-table-column>

            <el-table-column
              label="退库编号"
              prop="stockReturnCode"
              min-width="120"
            >
            </el-table-column>
            <el-table-column label="入库批次" prop="batchCode" min-width="120">
            </el-table-column>
            <el-table-column
              label="入库人"
              prop="applicantName"
              min-width="120"
            >
            </el-table-column>
            <el-table-column label="入库部门" prop="deptName" min-width="120">
            </el-table-column>
            <el-table-column
              label="入库日期"
              prop="applicantDate"
              min-width="120"
            >
            </el-table-column>
            <el-table-column
              label="入库仓位"
              prop="warehouseCode"
              min-width="120"
            >
            </el-table-column>
            <el-table-column
              v-if="dtlForm.importantDevice == 1"
              label="授权有效期"
              prop="validityPeriod"
              min-width="120"
            >
            </el-table-column>
            <el-table-column
              v-if="dtlForm.importantDevice == 1"
              label="厂家质保期"
              prop="expireDate"
              min-width="120"
            >
            </el-table-column>
            <el-table-column label="入库图片" prop="" min-width="120">
              <template #default="{ row }">
                <div v-if="row.fileList" class="image-content">
                  <el-image
                    v-for="(item, index) in row.fileList"
                    :key="index"
                    :preview-teleported="true"
                    style="width: 50px; height: 50px; margin-right: 5px"
                    :src="item.url"
                    :preview-src-list="showImg(item.url)"
                  >
                    <!-- <template #error>
                      <div class="image-slot">
                        <el-icon><icon-picture /></el-icon>
                      </div>
                    </template> -->
                  </el-image>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="备注" prop="remarks" min-width="120">
            </el-table-column>
          </el-table>
        </div>
      </el-collapse-item>
    </el-collapse>
    <el-dialog
      v-model="dialogVisible"
      title="主设备序列号"
      width="36%"
      :close-on-click-modal="false"
    >
      <QrCodeInfo :qrcodeData="qrcodeData" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { queryWarehouseList } from "@/api/pub";
import Upload from "@/components/Upload/index";
import QrCodeInfo from "@/components/qrCode/index";
import {
  showAddDtl,
  checkReturnAddDtl,
  temporaryMaterialDetail,
} from "@/api/stock/returnapply";
import { ElMessage, ElMessageBox } from "element-plus";
import dayjs from "dayjs";

const emit = defineEmits([
  // 客户新增组件显隐
  "selectionMaterialShow",
  // 更新客户新增组件显隐
  "update:selectionMaterialShow",
  //刷新父组件数据
  "refreshReturnList",
]);
//控制折叠面板
const activeNames = ref(["1", "2"]);
// 退库审核表单引用
const dtlFormRef = ref();
//控制查看二维码弹窗
const dialogVisible = ref(false);
//主设备物资序列号数据
const qrcodeData = ref([]);

const inboundData = ref([]);
const multipleTableRef = ref(null);

const loadingCheck = ref(false);
// 搜索参数
// 客户表单数据模板
const dtlFormTemplate = {
  stockReturnCode: "", //退库编号
  batchCode: "", //入库批次
  applicantName: "", //入库人,
  deptName: "", //入库部门
  applicantDate: "", //入库日期
  warehousingQuantity: null, //本次退库数量
  expireDate: "", //厂家质保期
  validityPeriod: "", //授权有效期
  warehouseId: null, //仓库id
  materialNumber: null, //主设备序列号
  remarks: "", //备注
  fileList: [],
  dtlList: [],
};

const data = reactive({
  // 客户表单
  dtlForm: JSON.parse(JSON.stringify(dtlFormTemplate)),

  // 客户表单校验规则
  queryRules: {
    applicantDate: [
      { required: true, message: "请选择入库日期", trigger: "change" },
    ],
    materialNumber: [
      {
        required: true,
        message: "主设备物资序列号不能为空",
        trigger: "change",
      },
    ],
    warehouseId: [
      { required: true, message: "仓库不能为空", trigger: "change" },
    ],
  },
  warehouseList: [], //仓库数据
  tempWarehouseId: null,
  tempWarehouseCode: null,
});

const {
  dtlForm,
  queryRules,
  warehouseList,
  tempWarehouseId,
  tempWarehouseCode,
} = toRefs(data);

// 表格加载效果
const loading = ref(false);

const tableIndex = ref(null);

/**
 * @description: 接收退库审核（入库数据）
 */
const handleMaterial = async (row, tabIndex) => {
  await showAddDtl(row.stockReturnDetailId).then((res) => {
    if (res.code === 200) {
      nextTick(() => {
        dtlForm.value.dtlList = res.data;
        dtlForm.value.importantDevice = row.importantDevice;
      });
    }
  });
  loadingCheck.value = false;
};
/**
 * @description: 退库审核（入库信息添加）
 */
const handleAdd = async (dtlFormRef, type) => {
  if (!dtlFormRef) return;
  await dtlFormRef.validate(async (valid) => {
    if (valid) {
      if (type == 2) {
        /* if(inboundData.value==null||inboundData.value.length==0||inboundData.value.length>1){
        ElMessage.error("请选择单条数据");
        return;
      }*/
        try {
          loadingCheck.value = true;
          await checkReturnAddDtl(dtlForm.value).then((res) => {
            if (res.code === 200) {
              ElMessage.success(res.msg);
              nextTick(() => {
                //修改

                for (let i = 0; i < dtlForm.value.dtlList.length; i++) {
                  if (
                    dtlForm.value.dtlList[i].stockReturnActualId ===
                    res.data.stockReturnActualId
                  ) {
                    dtlForm.value.dtlList[i] = JSON.parse(
                      JSON.stringify(res.data)
                    );
                  }
                }
              });
            }
          });
          loadingCheck.value = false;
        } catch (error) {
          loadingCheck.value = false;
        }
      } else {
        try {
          loadingCheck.value = true;
          await checkReturnAddDtl(dtlForm.value).then((res) => {
            if (res.code === 200) {
              ElMessage.success(res.msg);
              nextTick(() => {
                //修改
                dtlForm.value.dtlList[tableIndex.value] = JSON.parse(
                  JSON.stringify(res.data)
                );
              });
              handleBack();
            }
          });
          loadingCheck.value = false;
        } catch (error) {
          loadingCheck.value = false;
        }
      }
    } else {
      console.log("error submit!");
    }
  });
};
/**
 * @description: 退库审核（入库信息修改）
 */
const handleEdit = (row, tabIndex) => {
  tableIndex.value = tabIndex;
  let tempDtlList = dtlForm.value.dtlList;
  dtlForm.value = {
    ...JSON.parse(JSON.stringify(row)),
  };
  dtlForm.value.applicantId = row.tempApplicantId;
  dtlForm.value.applicantName = row.tempApplicantName;
  dtlForm.value.deptName = row.tempDeptName;
  dtlForm.value.applicantDate = dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss");
  if (dtlForm.value.warehouseId === null || dtlForm.value.warehouseId === "") {
    dtlForm.value.warehouseId = tempWarehouseId.value;
    dtlForm.value.warehouseCode = tempWarehouseCode.value;
  }

  dtlForm.value.dtlList = tempDtlList;
  if (dtlForm.value.importantDevice == 1) {
    //贵重物品
    dtlForm.value.inQty = 1;
    dtlForm.value.dtlList.forEach((element) => {
      if (element.status == 1) {
        element.inQty = 0;
        if (element.stockReturnActualId === row.stockReturnActualId) {
          element.inQty = 1;
        }
      }
    });
  } else {
    dtlForm.value.inQty = row.stockReturnQuantity;
    dtlForm.value.dtlList.forEach((element) => {
      element.inQty = row.stockReturnQuantity;
    });
  }
};

/**
 * @description: 处理合计
 */
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    // 只对amount这一列进行总计核算。
    if (
      column.property === "stockReturnQuantity" ||
      column.property === "inQty"
    ) {
      if (!values.every((value) => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return prev + curr;
          } else {
            return prev;
          }
        }, 0);
        sums[index] = sums[index].toFixed(2); // 保留2位小数，解决小数列合计精度缺失的问题
        // sums[index] += "元";
      } else {
        sums[index] = "";
      }
    }
  });
  return sums;
};

const handleBack = () => {
  emit("update:selectionMaterialShow", false);
  emit("refreshReturnList", false);
};

const handleWarehouseChange = (value) => {
  if (value) {
    const selectWarehouse = warehouseList.value.find(
      (item) => item.warehouseId === value
    );
    if (selectWarehouse) {
      dtlForm.value.warehouseCode = selectWarehouse.warehouseCode;
      tempWarehouseId.value = selectWarehouse.warehouseId;
      tempWarehouseCode.value = selectWarehouse.warehouseCode;
    }
  } else {
    dtlForm.value.warehouseCode = "";
  }
};

function uploadSuccess(response) {
  dtlForm.value.fileList.push({ ...response, businessType: 9 });
}

/**
 * @description: 删除文件
 * @param {Number} index 当前文件索引
 */
function uploadRemove(index) {
  dtlForm.value.fileList.splice(index, 1);
}

const showImg = (img) => {
  let imgArr = [];
  imgArr.push(img);
  return imgArr;
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  //仓库
  await queryWarehouseList(1).then((response) => {
    warehouseList.value = response;
  });
}
/**
 * @description: 输入后查询主设备物资序列号
 */
const handleMasterChange = async (val) => {
  if (val) {
    await temporaryMaterialDetail(val).then((res) => {
      if (res.code == 200) {
        dtlForm.value.expireDate = res.data.expireDate;
        dtlForm.value.validityPeriod = res.data.validityPeriod;
      }
    });
  } else {
    dtlForm.value.expireDate = "";
    dtlForm.value.validityPeriod = "";
  }
};
/**
 * @description: 查看主设备物资序列号
 */
const handleQrcode = async (row) => {
  qrcodeData.value = [];
  dialogVisible.value = true;
  qrcodeData.value.push({
    materialNumber: row.materialNumber,
  });
};

const checkSelect = (row) => {
  let isChecked = true;
  if (row.materialNumber) {
    // 判断里面是否存在某个参数
    isChecked = false;
  } else {
    isChecked = true;
  }
  return isChecked;
};

const handleSelectionChange = (list, row) => {
  inboundData.value = [];
  if (list.length === 0) {
    inboundData.value = [];
    return;
  }

  multipleTableRef.value.clearSelection();
  dtlForm.value.dtlList.forEach((ele) => {
    if (ele.stockReturnActualId === row.stockReturnActualId) {
      multipleTableRef.value.toggleRowSelection(ele, true);
      inboundData.value = [ele];
    }
  });

  if (inboundData.value.length) {
    let row = inboundData.value[0];

    let tempDtlList = dtlForm.value.dtlList;
    dtlForm.value = {
      ...JSON.parse(JSON.stringify(row)),
    };

    dtlForm.value.applicantId = row.tempApplicantId;
    dtlForm.value.applicantName = row.tempApplicantName;
    dtlForm.value.deptName = row.tempDeptName;
    dtlForm.value.applicantDate = dayjs(new Date()).format(
      "YYYY-MM-DD HH:mm:ss"
    );
    if (
      dtlForm.value.warehouseId === null ||
      dtlForm.value.warehouseId === ""
    ) {
      dtlForm.value.warehouseId = tempWarehouseId.value;
      dtlForm.value.warehouseCode = tempWarehouseCode.value;
    }

    dtlForm.value.dtlList = tempDtlList;

    let mapData = new Map();

    inboundData.value.forEach((item) => {
      mapData.set(item.stockReturnActualId, item);
    });
    dtlForm.value.dtlList.forEach((element) => {
      if (element.status == 1) {
        element.inQty = 0;
        if (mapData.get(element.stockReturnActualId) != null) {
          element.inQty = 1;
        }
      }
    });
    dtlForm.value.inQty = 1;
  } else {
  }
};

const cellClass = (row) => {
  if (row.columnIndex === 0) {
    return "disabledCheck";
  }
};

function rowClass({ row, rowIndex }) {
  if (dtlForm.value.stockReturnActualId == row.stockReturnActualId) {
    return "height:0;background-color:#ff9900";
  } else {
    return "height:0;";
  }
}

onMounted(() => {
  getDicts();
});

defineExpose({
  handleMaterial,
});
</script>

<style lang="scss" scoped>
.requestAdd {
  padding: 20px 20px;
  width: 100%;
  height: 100%;
  .request-info {
    padding: 20px 20px 5px 20px;
    background-color: #f0f0f0;
    margin: 10px 0;
  }
  .contact-info {
    padding-top: 20px;
  }

  :deep(.el-table) {
    th.el-table__cell {
      background: #f8f8f8 !important;
    }
  }
  :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
    width: 268px !important;
    height: 34px !important;
  }
  .search-input {
    width: 268px;
    height: 34px;
  }
  .image-content {
    width: 100%;
    line-height: 0px;
    overflow: auto;
  }
}
.auto-top {
  width: 100%;
  position: absolute;
  top: 0px;
  display: flex;
  font-weight: bold;
}
.auto-item {
  width: 125px;
  text-align: center;
  white-space: nowrap; /* 禁止换行 */
  overflow: hidden; /* 隐藏超出部分 */
  text-overflow: ellipsis; /* 使用省略号表示超出部分 */
}
.el-autocomplete .el-autocomplete-suggestion {
  max-height: 200px; /* 设置最大高度 */
  overflow-y: auto; /* 超出高度时显示滚动条 */
}
/* 去掉全选按钮 */
::v-deep .el-table .disabledCheck .cell .el-checkbox__inner {
  display: none !important;
}
</style>
